package com.github.llyb120.yaomq.client;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.github.llyb120.yaomq.server.MQService;
import com.github.llyb120.yaomq.server.MessageBuffer;
import com.github.llyb120.yaomq.server.WebSocketConfig;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @Author: Administrator
 * @Date: 2020/9/14 12:26
 */
public class MyWebSocketClient extends WebSocketClient {

    private String url;
    private String name;
    private String token;
    //自身的地址
    private String host;
    private int waitTime = 500;

    public MyWebSocketClient(String host, String url, String token) throws URISyntaxException {
        this(host, url, System.getenv("COMPUTERNAME"), token);
    }

    public MyWebSocketClient(String host, String url, String name, String token) throws URISyntaxException {
        super(new URI(String.format("ws://%s/_connect?name=%s&token=%s", url, URLUtil.encode(name), URLUtil.encode(token))));
        this.host = host;
        this.url = url;
        this.name = name;
        this.token = token;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        waitTime = 500;
        System.out.println("client connected");
    }

    @Override
    public void onMessage(String s) {
        System.out.println("client received message");
        System.out.println(s);

        MessageBuffer buffer = JSON.parseObject(s, MessageBuffer.class);
        System.out.println(buffer);
        System.out.println(host + buffer.getUrl());
        //请求自身
        HttpRequest request = null;
        if(buffer.getMethod().equalsIgnoreCase("get")){
            request = HttpUtil.createGet("http://" + host + buffer.getUrl());
        } else {
            request = HttpUtil.createPost("http://" + host + buffer.getUrl());
        }
        request.headerMap(buffer.getHeaders(), true);
        request.body(buffer.getBody());
        HttpResponse resp = request.execute();
        buffer.setStatus(resp.getStatus());
//        buffer.setHeaders(resp.hea);
        //copy headers
        resp.headers().forEach((k,v) -> {
            if (v == null) {
                buffer.getHeaders().put(k, null);
            } else {
                buffer.getHeaders().put(k, String.join("; ", v));
            }
        });
        buffer.setBody(resp.body());

        //发回
        this.send(JSON.toJSONString(buffer));
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        MQService.executorService.execute(() -> {
            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            waitTime = (int) Math.min(waitTime * 1.5, 15000);
            System.out.printf("will connect after %d \n", waitTime);
            this.reconnect();
        });
    }

    @Override
    public void onError(Exception e) {
//        e.printStackTrace();
    }

}
